package services;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import models.Inlink;

public class UpdateInlink {
	public UpdateInlink(String domainName, List<String> domains) {
		try {
			ObjectifyService.register(Inlink.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		Objectify ofy = ObjectifyService.begin();
		if (domains.size() > 0) {
			Inlink inlink = new Inlink();
			String name = "";
			List<String> dms = new ArrayList<String>();
			for (int i = 0; i < domains.size(); i++) {
				name = domains.get(i).replaceAll("(http|https)+://(www.)*", "");
				dms = new ArrayList<String>();
				try {
					inlink = ofy.get(new Key<Inlink>(Inlink.class, name));
					//inlink = ofy.query(Inlink.class).filter("domainName", name).get();
				} catch (Exception e) {
					inlink = null;
				}
				
				if (inlink != null) {
					dms = inlink.getDomains();
					if (!dms.contains(domainName) && domains.size() < 100) {
						dms.add(domainName);
						inlink.setDomains(dms);
						inlink.setDate(new Date());
						ofy.put(inlink);
					}
				} else {
					inlink = new Inlink();
					dms.add(domainName);
					inlink.setDomainName(name);
					inlink.setDomains(dms);
					inlink.setDate(new Date());
					ofy.put(inlink);
				}
			}
		}
		System.out.println("Update outlink success: " + domainName);
	}
}
